package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        User user = userMapper.findByUsername(username);

        return user;
    }

    /**
     * 分页
     *
     * @param bean
     * @return
     */
    public PageResult findPage(QueryPageBean bean) {
        PageHelper.startPage(bean.getCurrentPage(), bean.getPageSize());
        List<User> list = userMapper.findPage(bean.getQueryString());
        PageInfo pi = new PageInfo(list);
        return new PageResult(pi.getTotal(), list);
    }


    /**
     * 添加角色
     *
     * @param id
     * @param roleIds
     */
    public void addRole(Integer id, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                userMapper.addUserAndRole(id, roleId);
            }
        }

    }

    /**
     * 添加用户
     *
     * @param user
     */
    public void addUser(User user) {
        userMapper.addUser(user);
    }

    /**
     * 根据id查询角色
     *
     * @param id
     * @return
     */
    public List<Role> findById(String id) {
        List<Role> list = userMapper.findById(id);
        return list;
    }


    /**
     * 根据id删除用户
     *
     * @param id
     */
    public void del(Integer id) {
        //根据id查询中间表是否关联
        Long count = userMapper.findByUserId(id);
        if (count > 0) {
            //删除中间表
            userMapper.delByUserAndRole(id);
        }
        //删除用户
        userMapper.del(id);
    }


    public void findByName(String username) {
        userMapper.findByName(username);
    }


    /**
     * 查询全部
     *
     * @return
     */
    public List<Role> FindAll() {

        return userMapper.findAll();
    }


}
